﻿using System;
using System.Linq;
using ClientAPI.Network;
using System.Net.Sockets;
using System.Threading;
using System.Collections;

namespace ClientAPI
{
    class ChatProtocol
    {
        /// <summary>
        /// there is a major flaw all chat is held in memory currently will overload the memory
        /// </summary>

        ChatDictionary _chatDictionary;
        private Messenger _chatMessenger;
        bool _connected = false;
        string _userName;

        Thread _chatThread;

        public ChatProtocol()
        {
            _chatDictionary = ChatDictionary.Instance;
        }

        public void ChatConnect(Socket chatSocket, string userName)
        {
            _connected = true;
            _userName = userName;
            _chatMessenger = new Messenger(chatSocket, "CHAT ");

            _chatThread = new Thread(new ThreadStart(ChatHandler));
            _chatThread.Name = "ChatTHREAD";
            _chatThread.SetApartmentState(ApartmentState.STA);
            _chatThread.Start();

            _chatMessenger.SendMessage("$FRANK¶CHAT¶CONNECT¶" + CommandProtocol.Instance.GetUserName() + "¶");

        }

        public string GetLog(string userName)
        {
            string chatlog = "";
            ChatLog tempLog = new ChatLog();
            if (!_chatDictionary.GetChatDictionary().TryGetValue(userName, out tempLog))
            {
                System.Diagnostics.Debug.WriteLine("ChatArray import error!!!");
            }
            else
            {
                for (int i = 0; i <= tempLog.GetSize() - 1; i++)
                {
                    chatlog += (tempLog.GetMessageAt(i) + Environment.NewLine);
                }
            }
            return chatlog;
        }

        public string[] GetChatList()
        {
            return (string[])_chatDictionary.GetUserList().ToArray(typeof(string));
        }

        public string[] GetCurrentChats()
        {
            return _chatDictionary.GetChatDictionary().Keys.ToArray();
        }

        private void AddMessage(string otherUser, string message, bool yourMessage, bool allMessage)
        {
            string tempMessage;

            if (allMessage && !yourMessage)
            {
                tempMessage = otherUser + ": " + message;
                _chatDictionary.SetChatDictionary("ALL", tempMessage);
            }
            else if (!yourMessage)
            {
                tempMessage = otherUser + ": " + message;
                _chatDictionary.SetChatDictionary(otherUser, tempMessage);
            }
            else if (allMessage && yourMessage)
            {
                tempMessage = _userName + ": " + message;
                _chatDictionary.SetChatDictionary("ALL", tempMessage);
            }
            else if (yourMessage)
            {
                tempMessage = _userName + ": " + message;
                _chatDictionary.SetChatDictionary(otherUser, tempMessage);
            }

            Model.Instance.ChatMessageReceived();
        }

        public void SendChatMessage(string messageReceiver, string message)
        {
            bool tempBool = false;
            if (messageReceiver == "ALL")
            {
                tempBool = true;
            }
            AddMessage(messageReceiver, message, true, tempBool);

            _chatMessenger.SendMessage("$Frank¶CHAT¶" + _userName + "¶" + messageReceiver + "¶" + message + "¶");
        }

        public void ChatHandler()
        {
            do
            {
                string message = _chatMessenger.ReceiveChatMessage();

                if (message != null)
                {
                    System.Diagnostics.Debug.WriteLine("Chat Received: " + message);

                    string[] messageArray = message.Split('¶');
                    if (messageArray[messageArray.Length - 2] != null)
                    {
                        if (messageArray[messageArray.Length - 2] == "CONNECTED")
                        {
                            ArrayList tempString = new ArrayList();

                            foreach (string i in messageArray)
                            {
                                tempString.Add(i);
                            }

                            tempString.Remove("$FRANK");
                            tempString.Remove("CHAT");
                            tempString.Remove(_userName);
                            tempString.Remove("CONNECTED");
                            tempString.Remove(messageArray[messageArray.Length - 1]);

                            foreach (string i in tempString)
                            {
                                _chatDictionary.AddNewLogin(i);
                            }

                            Model.Instance.UpdateChatList();
                        }
                        else if (messageArray[messageArray.Length - 2] == "DISCONNECTED")
                        {

                        }
                        else if (messageArray[messageArray.Length - 2] == "OK")
                        {
                        }
                        else if (messageArray[1] == "CHAT")
                        {
                            if (messageArray[3] == "ALL" && messageArray[2] != _userName)
                            {
                                AddMessage(messageArray[2], messageArray[4], false, true);
                            }
                            else if (messageArray[3] == _userName)
                            {
                                AddMessage(messageArray[2], messageArray[4], false, false);
                            }
                            else
                            {
                            }
                        }
                        System.Diagnostics.Debug.WriteLine(GetLog("ALL"));
                    }
                }
            } while (_connected);
        }

        public void Disconnect()
        {
            _chatThread.Abort();
        }

        public void CloseLog(string user)
        {
            _chatDictionary.Close(user);
            Model.Instance.ChatMessageReceived();
        }
    }
}
